package me.sealer.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.sealer.ssm.constant.GiteeConstant;
import me.sealer.ssm.constant.GithubConstant;
import me.sealer.ssm.controller.dto.CommonResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * 功能描述： $ OpenAuth2Controller
 *
 * @author sealer
 * @email 1178884049@qq.com
 * @date 2019年12月12日 11时28分10秒
 */
@Controller
@RequestMapping("/oauth2")
@Api(tags = "open auth2 相关api")
public class OpenAuth2Controller {
    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;

    private static final String MY_GITHUB_CLIENT_ID = "8ffda36a06ccb0fe74a3";
    private static final String MY_GITHUB_CLIENT_SECRET = "853188b07a757e0c99205138bf56e94d44c41d74";

    private static final String MY_GITEE_CLIENT_ID = "96999b21ee76311576c8bf0e1441035d4b062c74b2158cdaaffa08ae8385189b";
    private static final String MY_GITEE_CLIENT_SECRET = "e4446ee18d1c0f71313f1b7d3453dc7bf07855f1a6e68d58874ad7c3a618d043";

    @ResponseBody
    @ApiOperation(value = "获取github授权地址")
    @GetMapping(value = "/code/github", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse<String> githubAuth() {
        String githubAuthUrl = GithubConstant.GITHUB_AUTHORIZE_URL
                + "?"
                + GithubConstant.CLIENT_ID
                + "="
                + MY_GITHUB_CLIENT_ID
                + "&"
                + GithubConstant.SCOPE
                + "="
                + "read:user";
        return new CommonResponse<>(githubAuthUrl);
    }

    @GetMapping(value = "/callback/github")
    @ApiOperation(value = "第三方授权登录之github回调")
    public ModelAndView githubAuth(@RequestParam("code") String code) {
        ModelAndView modelAndView = new ModelAndView("githubCode");
        modelAndView.addObject("github_code", code);
        return modelAndView;
    }

    @GetMapping(value = "/code/gitee")
    @ApiOperation(value = "获取gitee授权地址")
    public CommonResponse<String> giteeAuth() {
        String giteeAuthUrl = GiteeConstant.GITEE_AUTHORIZE_URL
                + "?"
                + GiteeConstant.CLIENT_ID
                + "="
                + MY_GITEE_CLIENT_ID
                + "&"
                + GiteeConstant.REDIRECT_URI
                + "="
                + "http://localhost:8888/ssm/callback/gitee"
                + "&"
                + "response_type=code";
        return new CommonResponse<>(giteeAuthUrl);
    }
}
